package com.wzy.level.detail.detailServlet;

import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
import com.wzy.Jdbc封装.pojo.News_detail;
import com.wzy.level.detail.detailService.detailService;
import com.wzy.level.detail.detailServiceImpl.detailServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@WebServlet("/detail_form_mid")
public class detail_form_insert_update extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//        req.setCharacterEncoding("utf-8");
//    int id = Integer.parseInt(request.getParameter("id"));
//    int categoryId = Integer.parseInt(request.getParameter("categoryId").trim());
//    String title = request.getParameter("title");
//    String summary = request.getParameter("summary");
//    String content = request.getParameter("content");
        int id =0;
        int categoryId =0;
        String title =null;
        String summary =null;
        String content =null;
        String author =null;
        String screateDate =null;
        String smodifyDate =null;

        int state =0;
        //picPath
        //上传图片
        boolean isMultipartFile = ServletFileUpload.isMultipartContent(req);
        String path = "D:\\web_project\\src\\main\\webapp\\images";
        String pa = "http://localhost:8080/images/";
        File o_file = new File(path);

        String picPath = null;
        if(!o_file.exists()){
            o_file.mkdir();
        }

        if(isMultipartFile){
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
//      String charset  =  request.getCharacterEncoding();
//      if  (charset  !=   null ) {
//        servletFileUpload.setHeaderEncoding(charset);
//      }
            List<FileItem> list = null;
            try {
                list = servletFileUpload.parseRequest(req);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            Iterator<FileItem> iterator = list.iterator();
            while(iterator.hasNext()){
                FileItem item = iterator.next();
                boolean formField = item.isFormField();
                if(!formField){
                    String fileUpdate = item.getName();
                    File m_file = new File(fileUpdate);
                    if(m_file.getName()!=null && !(m_file.getName().equals(""))){
                        File file = new File(path + "\\" + m_file.getName());
                        try {
                            item.write(file);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        System.out.println(file.getPath());
                        picPath =pa+file.getName();
                        System.out.println(picPath);
                    }
                }else {
                    String fieldName = item.getFieldName();
                    if(fieldName.equals("id")){
                        id = Integer.parseInt(item.getString());
                    }else if(fieldName.equals("categoryId")){
                        categoryId = Integer.parseInt(item.getString().trim());
                    }else if(fieldName.equals("title")){
//            title = item.getString();
                        title = new String((item.getString("iso8859-1")).getBytes("iso8859-1"),"utf-8");
                    }else if(fieldName.equals("summary")){
//           summary = item.getString();
                        summary = new String((item.getString("iso8859-1")).getBytes("iso8859-1"),"utf-8");
                    }else if(fieldName.equals("content")){
//            content = item.getString();
                        content = new String((item.getString("iso8859-1")).getBytes("iso8859-1"),"utf-8");
                    }else if(fieldName.equals("author")){
//            author = item.getString();
                        author = new String((item.getString("iso8859-1")).getBytes("iso8859-1"),"utf-8");
                    }else if(fieldName.equals("date")){
                        screateDate = item.getString().trim();
                    }else if(fieldName.equals("date1")){
                        smodifyDate = item.getString().trim();
                    }else if(fieldName.equals("state")){
                        state = Integer.parseInt(item.getString());
                    }
                }
            }
        }

        //上传结束

        Date createDate = null;
        Date modifyDate = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
        System.out.println(simpleDateFormat);
        try {
                createDate = simpleDateFormat.parse(screateDate);

                modifyDate = simpleDateFormat.parse(smodifyDate);


            simpleDateFormat.setLenient(false);
        }catch (ParseException | java.text.ParseException e){
            e.printStackTrace();
        }



        News_detail news_detail = new News_detail();


//    URLEncoder.encode(picPath,"utf-8");
//    new String(picPath.getBytes(StandardCharsets.UTF_8));

//    title.getBytes(StandardCharsets.UTF_8);

        news_detail.setCategoryId(categoryId);
        news_detail.setTitle(title);
        news_detail.setSummary(summary);
        news_detail.setContent(content);
        news_detail.setPicPath(picPath);
        news_detail.setAuthor(author);
        news_detail.setDate(createDate);
        news_detail.setDate1(modifyDate);



//    String sstate = request.getParameter("state");
//    int state = Integer.parseInt(sstate);

        detailService detail = new detailServiceImpl();

//        PrintWriter writer = resp.getWriter();


        if(state==0){
            news_detail.setId(id);
            int update = detail.update(news_detail);
            req.setAttribute("update",update);
            if(update>0){
//                writer.println(1);
//                req.getRequestDispatcher("/pageManage?cate=1").forward(req,resp);
                resp.sendRedirect("http://localhost:8080//pageManage2?cate=1");
            }else {
                System.out.println("修改失败");
            }
        }else if(state == 1){
            int insert = detail.insert(news_detail);
            req.setAttribute("insert",insert);
            if(insert>0){
//                writer.println(1);
                resp.sendRedirect("http://localhost:8080//pageManage2?cate=1");
            }else {
                System.out.println("新增失败");
            }

//            writer.flush();
//            writer.close();

        }



    }
}
